#include "easyAI.h"
#include "step.h"
#include <QTimer>
#include "mainwindow.h"

EasyAI::EasyAI(MainWindow* _mainWindow):Board(_mainWindow)
{

}

void EasyAI::clickHandler(int id, int row, int col)
{
    if (isRedTurn)
        Board::clickHandler(id, row, col);
    if (!isRedTurn)
        QTimer::singleShot(100, this, SLOT(computerMove()));
}

void EasyAI::computerMove()
{
    Step *bestStep = NULL;
    int maxMinValues = INT_MIN; //人下完电脑的最低分中最高的

    clock_t startTime = clock();
    QVector<Step *> steps;
    getAllCanSteps(steps);
    //模拟走棋算出最高分
    while (steps.count()) {
        Step *step = steps.back();
        movePiece(step->fromId, step->rowTo, step->colTo);
        if (step->toId >= 0)
            pieces[step->toId].isAlive = false;

        int tmpScore = calcScore();
        //还原
        if (step->toId >= 0)
            pieces[step->toId].isAlive = true;
        movePiece(step->fromId, step->rowFrom, step->colFrom);

        if (tmpScore > maxMinValues) {
            maxMinValues = tmpScore;
            if (bestStep)
                delete bestStep;
            bestStep = step;
        } else
            delete step;
        steps.removeLast();
    }
    clock_t endTime = clock();
    qDebug() << "耗时：" << endTime - startTime;

    saveStep(bestStep->fromId, bestStep->rowTo, bestStep->colTo, bestStep->toId);
    if (bestStep->toId >= 0)
        pieces[bestStep->toId].isAlive = false;
    movePiece(bestStep->fromId, bestStep->rowTo, bestStep->colTo);
    delete bestStep;
    if(!checkWin())
    {
        mainWindow->resetTimer(true);
        blackStep++;
        mainWindow->updateStep(false,blackStep);
    }

    update();
}

void EasyAI::getAllCanSteps(QVector<Step *> &steps)
{
    int min = 0, max = 16;
    if (!isRedTurn) {
        min = 16;
        max = 32;
    }
    for (int i = min; i < max; i++)
        if (pieces[i].isAlive)
            for (int row = 1; row < 11; row++)
                for (int col = 1; col < 10; col++) {
                    int targetId = getPiece(row, col);
                    if (targetId >= 0 && pieces[i].red == pieces[targetId].red)
                        continue;
                    if (canMove(i, row, col)) {
                        Step *step = new Step;
                        step->rowFrom = pieces[i].row;
                        step->colFrom = pieces[i].col;
                        step->rowTo = row;
                        step->colTo = col;
                        step->fromId = i;
                        step->toId = targetId;
                        steps.append(step);
                    }
                }
}

int EasyAI::calcScore()
{
    static int score[] = {999, 90, 40, 45, 17, 18, 15};
    int redSum = 0, blackSum = 0;
    for (int i = 0; i < 32; i++)
        if (pieces[i].isAlive)
            if (i < 16)
                redSum += score[pieces[i].type];
            else
                blackSum += score[pieces[i].type];
    return blackSum - redSum;
}
